package y2019.date0927.notifywaite;

import org.junit.jupiter.api.Test;
import y2019.date0927.notifywaite.base.BasePCModel;

/**
 * 生产者消费者model。加锁，加wait、notify
 *
 * @author lu
 * @date 2019-09-27
 */
public class ProductConsumerModel_2 extends BasePCModel {

    private final int count = 10;
    private Object lock = new Object();
    private String name = "苹果";
    private int productNo = 0;//苹果编号
    private volatile boolean isProduced;

    @Test
    public void produce() throws InterruptedException {
        synchronized (lock) {
            for (int i = 0; i < count; i++) {
                //编号增加，模拟制作不同编号苹果，方便理解，制作过程的业务逻辑省略
                if (isProduced) {
                    //如果已经生产，等待消费了再继续
                    lock.wait();
                } else {
                    productNo++;
                    System.out.println(String.format("生产中，%s编号%d", name, productNo));
                    isProduced = true;
                    //生产完成，通知去消费
                    lock.notify();
                }
            }
        }
    }

    @Test
    public void consume() throws InterruptedException {
        synchronized (lock) {
            for (int i = 0; i < count; i++) {
                if (isProduced) {//如果有产品，消费并通知
                    System.out.println(String.format("消费中，%s编号%d", name, productNo));
                    isProduced = false;
                    lock.notify();
                } else {
                    //没产品就等待。单独运行会导致一直等待
                    lock.wait();
                }

            }
        }
    }


}
